<template>
  <h1 style="font-size: 1.25rem; margin-bottom: 1.25rem">
    {{ $t("交易记录") }}
  </h1>

  <el-card>
    <div class="flex justify-between">
      <el-form style="flex: 1" :inline="true" :model="filterForm">
        <el-form-item>
          <el-input
            v-model="filterForm.card_number"
            :placeholder="$t('卡号后四位')"
            clearable
            style="width: 100%"
            @change="filterList"
          >
            <template #append>
              <el-button icon="Search" @click="filterList" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="filterForm.timeData"
            clearable
            type="datetimerange"
            :range-separator="$t('至')"
            :start-placeholder="$t('开始日期')"
            :end-placeholder="$t('截止日期')"
            @change="filterList"
            :default-time="pickerDefaultTime"
          />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="filterForm.status"
            style="width: 150px"
            clearable
            :placeholder="$t('订单状态')"
            @change="filterList"
          >
            <el-option
              v-for="item in orderStatus"
              :key="item.key"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="filterForm.currency"
            style="width: 150px"
            clearable
            :placeholder="$t('币种')"
            @change="filterList"
          >
            <el-option
              v-for="item in currencyList"
              :key="item.key"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="info" icon="Download" @click="onExport">{{
          $t("导出")
        }}</el-button>
        <el-button
          type="danger"
          icon="Upload"
          @click="uploadDialogVisible = true"
          >{{ $t("导入") }}</el-button
        >
      </div>
    </div>

    <el-table :data="orderList" v-loading="loading">
      <el-table-column
        prop="transaction_date"
        :label="$t('日期')"
        align="center"
        width="180"
        :formatter="formatterTime"
      />
      <el-table-column align="center" :label="$t('金额')" width="150">
        <template #default="scope">
          -{{ numberToCurrencyNo(scope.row.transaction_amount) }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="transaction_currency"
        :label="$t('币种')"
      />
      <el-table-column
        prop="masked_card_number"
        :label="$t('卡号')"
        width="150"
        align="center"
      />
      <el-table-column prop="category_name" :label="$t('状态')" align="center">
        <template #default="scope">
          <el-tag
            :type="
              getOrderStatusName(scope.row.status)
                ? getOrderStatusName(scope.row.status).type
                : 'info'
            "
          >
            {{
              getOrderStatusName(scope.row.status)
                ? getOrderStatusName(scope.row.status)?.name
                : scope.row.status
            }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="card_nickname"
        :label="$t('卡片别名')"
        align="center"
      />
      <el-table-column prop="description" :label="$t('描述')" align="center">
        <template #default="scope">
          {{ scope.row.description ? scope.row.description : "--" }}
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        align="center"
        :label="$t('操作')"
        width="150"
      >
        <template #default="scope">
          <el-button
            round
            icon="MoreFilled"
            class="cursor-pointer"
            @click="showCurrentDetail(scope.row)"
            >{{ $t("查看") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex justify-center mt-5">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageable.total"
        :default-page-size="pageable.pageSize"
        :default-current-page="pageable.pageNum"
        :page-sizes="[10, 25, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
  <!-- 导入弹窗 -->
  <el-dialog
    v-model="uploadDialogVisible"
    title="Excel文件导入"
    width="700"
    center
    @close="onCloseDialog"
  >
    <div v-if="uploadVisible">
      <el-upload
        class="upload-demo"
        drag
        ref="uploadRef"
        accept="xlsx,xls"
        :before-upload="beforeUpload"
        :action="config.cardFile_upload"
        :on-success="handleUploadSuccess"
        :headers="TOKENT_HEADER"
        :show-file-list="false"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          {{ $t("将Excel文件拖到此处，或者") }}<em>{{ $t("点击上传") }}</em>
          <!--Drop Excel file here or <em>click to upload</em>-->
        </div>
        <template #tip>
          <div class="el-upload__tip">
            <p class="text-[#e54c5f]">
              {{
                $t(
                  "注：上传的Excel文件必须为从交易记录导出的文件，并确保格式不变且补充的机票内容正确!"
                )
              }}
            </p>
          </div>
        </template>
      </el-upload>
    </div>
    <div v-else style="max-height: 400px; overflow-y: auto">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column
          prop="transaction_id"
          :label="$t('交易ID')"
          width="180"
        />
        <el-table-column prop="saved" :label="$t('是否保存')" width="120">
          <template #default="scope">
            <span
              :style="scope.row.saved === 1 ? 'color: green' : 'color: red'"
            >
              {{ scope.row.saved === 1 ? `${$t("是")}` : `${$t("否")}` }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="msg" :label="$t('说明信息')" />
      </el-table>
    </div>
  </el-dialog>

  <el-drawer
    v-model="showDrawer"
    :title="$t('卡片交易详情')"
    size="35%"
    @close="closeDrawer"
  >
    <el-card v-loading="loading">
      <div class="detailRow">
        <span class="rowName">{{ $t("订单状态") }}</span>
        <el-tag
          :type="
            getOrderStatusName(state.detailInfo.status)
              ? getOrderStatusName(state.detailInfo.status)?.type
              : 'info'
          "
          >{{
            getOrderStatusName(state.detailInfo.status)
              ? getOrderStatusName(state.detailInfo.status)?.name
              : state.detailInfo.status
          }}</el-tag
        >
      </div>
      <span class="text-xl font-medium"
        >-{{ numberToCurrencyNo(state.detailInfo.transaction_amount) }}</span
      >
      <span class="ml-2 text-sm">{{
        state.detailInfo.transaction_currency
      }}</span>
      <p class="mt-2 text-sm">{{ state.detailInfo.merchant?.name }}</p>
      <el-divider />
      <h3 class="mb-4 font-medium text-large">{{ $t("交易明细详情") }}</h3>
      <div
        v-for="(item, index) in infoDetailList"
        :key="index"
        class="detailRow"
        v-show="item.isShow"
      >
        <span class="rowName">{{ item.name }}</span>
        <span class="rowValue">{{ item.value }}</span>
      </div>
      <h3 class="mt-10 mb-4 font-medium text-large">{{ $t("卡片详情") }}</h3>
      <div
        v-for="(item, index) in cardDetailList"
        :key="index"
        class="detailRow"
        v-show="item.isShow"
      >
        <span class="rowName">{{ item.name }}</span>
        <span class="rowValue">{{ item.value }}</span>
      </div>
      <div v-if="Object.keys(state.ticket_List).length > 0">
        <h3 class="mt-10 mb-4 font-medium text-large">{{ $t("机票信息") }}</h3>
        <div
          v-for="(item, index) in ticket_List"
          :key="index"
          class="detailRow"
          v-show="item.isShow"
        >
          <span class="rowName">{{ item.name }}</span>
          <span class="rowValue">{{ item.value }}</span>
        </div>
      </div>
    </el-card>
  </el-drawer>
</template>
<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import {
  timestamp,
  formatterTime,
  numberToCurrencyNo,
  exportExcel,
  formatDates,
  pickerDefaultTime,
} from "@/utils/utils";
import { PayCurrencyApi } from "@/api/account/index";
import {
  GetCardsTransactions,
  GetCardsTransactionsDetail,
} from "@/api/card/index";
import { config, TOKENT_HEADER } from "@/config/index";

const currencyList = ref([]); //币种
const loading = ref(false);
const uploadDialogVisible = ref(false);
const uploadVisible = ref(true);

const orderStatus = reactive([
  { key: 1, name: `${t("交易成功")}`, value: "APPROVED", type: "success" },
  { key: 2, name: `${t("处理中")}`, value: "PENDING", type: "warning" },
  { key: 3, name: `${t("拒绝")}`, value: "FAILED", type: "danger" },
  { key: 4, name: `${t("被取消")}`, value: "REVERSED", type: "danger" },
  { key: 4, name: `${t("交易成功")}`, value: "CLEARED", type: "success" },
]);

const route = useRoute();

const orderList = ref([]);
const tableData = ref([]);

// 分页
const pageable = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const state = reactive({
  detailInfo: {},
  ticket_List: {},
});

// 交易明细详情
const infoDetailList = computed(() => {
  let arr = [
    {
      name: `${t("交易金额")}`,
      value: `-${numberToCurrencyNo(state.detailInfo.transaction_amount)} ${
        state.detailInfo.transaction_currency
      }`,
      isShow: true,
    },
    {
      name: `${t("帐单金额")}`,
      value: `-${numberToCurrencyNo(state.detailInfo.billing_amount)} ${
        state.detailInfo.billing_currency
      }`,
      isShow: true,
    },
    {
      name: `${t("流水号")}`,
      value: state.detailInfo.transaction_id,
      isShow: true,
    },
    {
      name: `${t("商户名")}`,
      value: state.detailInfo.merchant?.name,
      isShow: true,
    },
    {
      name: `${t("商户位置")}`,
      value: `${state.detailInfo.merchant?.country}  ${state.detailInfo.merchant?.city}`,
      isShow: true,
    },
    {
      name: `${t("交易时间")}`,
      value: `${formatDates(state.detailInfo.createtime)}`,
      isShow: true,
    },
  ];
  return arr;
});

// 卡片详情
const cardDetailList = computed(() => {
  let arr = [
    {
      name: `${t("卡片别名")}`,
      value: state.detailInfo.card_nickname,
      isShow: true,
    },
    {
      name: `${t("卡片号码")}`,
      value: state.detailInfo.masked_card_number,
      isShow: true,
    },
  ];

  return arr;
});

// 机票详情
const ticket_List = computed(() => {
  let arr = [
    {
      name: `${t("订单编号")}`,
      value: state.ticket_List.order_no,
      isShow: true,
    },
    {
      name: `${t("票号")}`,
      value: state.ticket_List.ticket_no,
      isShow: true,
    },
    {
      name: `${t("出票日期")}`,
      value: state.ticket_List.issue_date,
      isShow: true,
    },
    {
      name: `${t("乘客姓名")}`,
      value: state.ticket_List.passenger_name,
      isShow: true,
    },
    {
      name: "PNR",
      value: state.ticket_List.pnr,
      isShow: true,
    },
    {
      name: `${t("行程")}`,
      value: state.ticket_List.route,
      isShow: true,
    },
    {
      name: `${t("币种")}`,
      value: state.ticket_List.currency,
      isShow: true,
    },
    {
      name: `${t("数量")}`,
      value: state.ticket_List.number,
      isShow: true,
    },
    {
      name: `${t("单价")}`,
      value: state.ticket_List.price,
      isShow: true,
    },
    {
      name: `${t("人民币金额")}`,
      value: state.ticket_List.cny_amount,
      isShow: true,
    },
  ];

  return arr;
});

// 获取币种
const getCurrencyData = async () => {
  const res = await PayCurrencyApi();
  if (res.length) {
    currencyList.value = res.map((item) => {
      return { value: item, label: item };
    });
  }
};

// 参数
const param = reactive({
  page: pageable.pageNum,
  pagesize: pageable.pageSize,
});

// 表格数据
const getTransactionsList = async (listQuery) => {
  try {
    loading.value = true;
    console.log(listQuery, "listQuery");
    const { page, list } = await GetCardsTransactions({
      ...{ page: pageable.pageNum, pagesize: pageable.pageSize },
      ...listQuery,
    });
    orderList.value = list || [];
    pageable.total = page.total_count || 0;
    loading.value = false;
  } catch (e) {
    loading.value = false;
    return false;
  }
};

// 订单状态
const getOrderStatusName = (status) => {
  return orderStatus.find((i) => status === i.value);
};

const currentOrderNo = ref("");
const showDrawer = ref(false);

// 详情
const showCurrentDetail = (row) => {
  showDrawer.value = true;
  currentOrderNo.value = row.transaction_id;
  loading.value = true;
  GetCardsTransactionsDetail({ transaction_id: row.transaction_id })
    .then((res) => {
      state.detailInfo = res || {};
      state.ticket_List = res.ticket_info || {};
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
      return false;
    });
};

const handleCurrentChange = async (number) => {
  pageable.pageNum = number;
  await getTransactionsList();
};
// 条数
const handleSizeChange = (number) => {
  pageable.pageSize = number;
  getTransactionsList();
};
//筛选组件
const filterForm = reactive({
  card_number: "",
  status: "",
  currency: "",
  timeData: [],
});
const filterList = async (e) => {
  let query = {
    ...param,
    ...filterForm,
  };
  if (query.timeData) {
    query.date_start = query.timeData[0]
      ? timestamp(query.timeData[0].valueOf())
      : "";
    query.date_end = query.timeData[1]
      ? timestamp(query.timeData[1].valueOf())
      : "";
    delete query.timeData;
  }
  const newQuery = Object.entries(query).reduce((acc, [key, value]) => {
    if (value) {
      acc[key] = value;
    }
    return acc;
  }, {});
  pageable.page = 1;
  await getTransactionsList(newQuery);
};

const closeDrawer = () => {
  showDrawer.value = false;
};

const onCloseDialog = () => {
  uploadVisible.value = true;
};

// 导出
const onExport = async () => {
  let query = { ...param, ...filterForm };
  const data = Object.assign(query, {
    export: 1,
    pagesize: 9999999,
  });
  try {
    const res = await GetCardsTransactions(data, "blob");
    exportExcel(res, "card_transactions");
  } catch {}
};

const uploadRef = ref("");

const beforeUpload = (file) => {
  const types = file.name.split(".")[1];
  const fileType = ["xlsx", "xls"].some((item) => {
    return item === types;
  });
  if (!fileType) {
    ElMessage.error("文件格式错误，请重新选择文件！");
    return false;
  }
  if (file.size / 1024 / 1024 > 1) {
    ElMessage.error("上传文件大小不能超过 1M !");
    return false;
  }
};

// 照片上传
const handleUploadSuccess = (res) => {
  if (res.code === 0) {
    ElMessage({
      message: t("上传成功"),
      type: "success",
    });
    uploadVisible.value = false;
    tableData.value = res.data || [];
  } else {
    ElMessage({
      message: t("上传失败"),
      type: "error",
    });
    return false;
  }
};
onMounted(() => {
  getTransactionsList({ card_id: route.query.card_id });
  getCurrencyData();
});
</script>
<style lang="scss" scoped>
.detailRow {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0.5rem;

  .rowName {
    min-width: 30%;
    flex-shrink: 0;
    display: flex;
    align-items: center;
  }

  .rowValue {
    word-break: break-all;
    text-align: right;
  }
}
</style>
